home *** CD-ROM | disk | FTP | other *** search
- Path: lrz-muenchen.de!news
- From: watzka@stat.uni-muenchen.de (Kurt Watzka)
- Newsgroups: comp.lang.c
- Subject: Re: accessing structures (newbie question)
- Date: 19 Feb 1996 15:04:00 GMT
- Organization: Leibniz-Rechenzentrum, Muenchen (Germany)
- Distribution: world
- Message-ID: <4ga3h0$h20@sparcserver.lrz-muenchen.de>
- References: <4g8gic$o6u@news1.sunbelt.net>
- NNTP-Posting-Host: sun2.lrz-muenchen.de
-
- dking@SunBelt.Net writes:
-
- >Ok. having trouble accessing structure. here I define a pointer and malloc the
- >memory:
-
- You don't have problems accessing a struct, you have problems
- accessing an array.
-
- >struct picture *photos;
- >photos = (struct picture *)malloc(1000 * sizeof(picture));
-
- >now I try to store data into structures...
-
- > for (x=0;x<num_of_files;x++)
- > {
- > strncpy(photos->filename, filelist[x],12);
- > strncpy(photos->diskname, inputdisk,12);
- > strncpy(photos->indexname, inputindex,12);
- > }
-
- Why do you allocate space for 1000 pictures and use "num_of_files" of
- them? To access the "x"th element of an array, it is customary to
- use syntax like
-
- strncpy(photos[x].filename, filelist[x], 12);
-
- You do it for "filelist", so why don't you want to do it for "photos",
- too?
-
- >now I try to read data...
-
-
- >for (x=0;x<num_of_files;x++)
- >{
- >
- >printf("%sdisk%sindex%s\n",photos->filename,photos->diskname,photos->indexname
- >; }
-
- >Obviously I'm pointing to the first of the 1000 structures the entire time.
- >Now for the 60,000 dollar question: HOW do I access the rest of the
- >structures? My tutuorial doesnt have any examples of accessing MALLOCed
- >structures. The one example on structures defines it as an array (struct
- >picture *photos[x] ) but 1000 elements is too large an array and the example
- >with malloc uses floating point data accessed by using (photos[x]) which
- >doesnt work either with the strnccpy or with the -> operator.
-
- Well, "photos[x]" is equivalent to "*(photos + x)", so if "photos" is
- a pointer to a "struct picture", then "photos[x]" is a plain "struct
- picture", not a pointer to one. This is why the "->" operator will not
- work for "photos[x]". You have to fall back to ".". You could, of course,
- do something like:
-
- struct picture *photos, *p;
- photos = (struct picture *)malloc(num_files * sizeof(picture));
-
- for (x=0, p = photos; x<num_of_files; x++, p++)
- {
- strncpy(p->filename, filelist[x],12);
- strncpy(p->diskname, inputdisk,12);
- }
-
- Kurt
- --
- | Kurt Watzka Phone : +49-89-2180-6254
- | watzka@stat.uni-muenchen.de
- | ua302aa@sunmail.lrz-muenchen.de
-
-